<template>
  <!-- 组件中只有一个弹窗 -->
  <el-dialog
      v-model="bomAddWinDialogVisible"
      title="物料产品选择"
      width="70%"
      @close="handleClose"
  >
    <template #default>
      <el-row style="margin: 10px">
        <el-col :span="3.5" style="margin-top: 10px">
          <!-- 树列表 -->
          <el-input
              v-model="filterText"
              style="width: 200px"
              placeholder="筛选关键词"
              :prefix-icon="Search"
              clearable/>

          <el-tree
              ref="treeRef"
              style="max-width: 200px;margin-top: 20px"
              class="filter-tree"
              :data="classifys"
              :props="{children: 'children',label: 'classifyName'}"
              default-expand-all
              :filter-node-method="filterNode"
              :expand-on-click-node="false"
              @node-click="classifySelect"
              @node-expand="handleNodeExpand"
              @node-collapse="handleNodeCollapse"/>
        </el-col>
        <el-col :span="19" style="margin-top: 5px">
          <!-- 搜索栏-->
          <el-row style="padding: 5px;margin-left: 15px">
            <el-col :span="24">
              <el-form :model="materialQuery" inline>
                <el-form-item label="物料编码">
                  <el-input v-model="materialQuery.materialCode" clearable/>
                </el-form-item>

                <el-form-item label="物料名称">
                  <el-input v-model="materialQuery.materialName" clearable/>
                </el-form-item>

                <el-form-item>
                  <el-button @click="loadMaterials" type="primary"> <el-icon><Search /></el-icon>&nbsp搜索</el-button>
                  <el-button @click="referMaterials"> <el-icon><Refresh /></el-icon>&nbsp重置</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>

          <!-- 数据列表 -->
          <el-row style="margin: 10px 5px;padding:0px 15px;">
            <el-col :span="24">
              <el-table :data="materials" border stripe ref="materialTable">
                <el-table-column type="selection" width="55"/>
                <el-table-column prop="materialCode" width="130px" label="物料编码"/>
                <el-table-column prop="materialName" width="110px" label="物料名称"/>
                <el-table-column prop="specification" width="110px" label="规格型号"/>
                <el-table-column prop="materialUnitCode" width="90px" label="单位"/>
                <el-table-column prop="kindType" width="100px" label="物料/产品">
                  <template #default="scope">
                    <el-col v-if="scope.row.kindType == 1">物料</el-col>
                    <el-col v-if="scope.row.kindType == 2">产品</el-col>
                  </template>
                </el-table-column>
                <el-table-column prop="kindName" width="120px" label="所属分类"/>
                <el-table-column prop="createTime" width="120px" label="创建时间"/>
              </el-table>
            </el-col>
          </el-row>

          <el-footer>
            <!--  分页栏 -->
            <el-row :span="5" style="margin-left: 650px">
              <el-col :span="1.5" style="color: dimgray;padding: 10px;margin-top: 5px">
                共 {{total}} 条
              </el-col>
              <el-col :span="2" style="padding: 10px">
                <el-pagination @change="changePage" background layout="prev, pager, next" :total="total"/>
              </el-col>
            </el-row>
          </el-footer>
        </el-col>
      </el-row>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelnewBom">取消</el-button>
        <el-button type="primary" @click="newBomSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {onMounted, ref, watch} from 'vue'
import {ElMessage, ElTree} from "element-plus";
import bomRequest from "@/api/bom.js";
import {Search} from "@element-plus/icons-vue";
import classifyRequest from "@/api/classify.js";
import materialRequest from "@/api/material.js";
// 申明这个组件的事件  editComplete
const emits = defineEmits(['addComplete','cancelBomAdd'])

// 弹窗标记
let bomAddWinDialogVisible = ref(false);

let props = defineProps(["materialId","isShow"]);
// 封装搜索条件
let materialQuery = ref({});
// 定义数组保存所有物料信息
let materials = ref([]);
// 定义数组保存所有分类信息
let classifys = ref([]);
// 左半边查询
let filterText = ref('')
let treeRef = ref(null) // 移除了类型注解
// 总条数，默认0
let total = ref(0);
// 当前页码，默认1
let curPage = ref(1);
// 查询结果
let materialTable = ref(null);
const filterNode = (value, data) => { // 移除了类型注解
  if (!value) return true
  return data.classifyName.includes(value)
}

function handleNodeExpand(node, nodeComponent, e) {
  // 检查点击的元素是否是展开/折叠图标
  let target = e.target;
  while (target && target !== nodeComponent.$el) {
    if (target.classList.contains('el-tree-node__expand-icon')) {
      node.expanded = true;
      return;
    }
    target = target.parentNode;
  }
}

function handleNodeCollapse(node, nodeComponent, e) {
  // 检查点击的元素是否是展开/折叠图标
  let target = e.target;
  while (target && target !== nodeComponent.$el) {
    if (target.classList.contains('el-tree-node__expand-icon')) {
      node.expanded = false;
      return;
    }
    target = target.parentNode;
  }
}

/**
 * 菜单激活事件
 * @param data 选中节点的数据
 * @param node 选中节点的 Node 对象
 */
function classifySelect(data) {
  let kindIds = ref([]);
  // 递归函数来处理节点及其子节点
  function processClassifies(classifies) {
    classifies.forEach(classify => {
      // 将当前节点的 classifyId 添加到 kindIds 数组
      kindIds.value.push(classify.classifyId);
      // 如果当前节点有子节点，递归处理子节点
      if (classify.children && classify.children.length > 0) {
        processClassifies(classify.children);
      }
    });
  }
  // 将当前点击的 classifyId 添加到 kindIds 数组
  kindIds.value.push(data.classifyId);
  // 发送请求获取树形数据
  classifyRequest.getTree(data.classifyId, res => {
    // 确保 res.data 不是 null 或 undefined
    if (res && res.data) {
      // 使用递归函数处理获取到的分类数据
      processClassifies(res.data);
    }
    // 将数组赋值给查询条件中的 classify
    materialQuery.value.classify = kindIds.value;
    // 调用 loadMaterials 函数
    loadMaterials();
  });
}

/**
 * 加载物料列表
 */
function loadMaterials() {
  // 调用API来查询项目列表
  materialRequest.loadMaterials(materialQuery.value, curPage.value, 10, res => {
    // 这里的res就是后端返回的结果
    // 总条数赋值
    total.value = res.data.total;
    // 将查询的列表赋值给projects
    materials.value = res.data.list;
  })
}

/**
 * 重置按钮事件
 */
function referMaterials(){
  materialQuery.value.materialCode = null;
  materialQuery.value.materialName = null;
  loadMaterials();
}

// 分页事件
function changePage(value) {
  curPage.value = value;
  loadMaterials();
}

/**
 * 取消新增按钮事件
 */
function cancelnewBom(){
  // 取消选中
  materialTable.value.clearSelection();
  bomAddWinDialogVisible.value = false;
  emits("cancelBomAdd")
}

/**
 * 关闭窗体前的回调函数
 */
function handleClose(){
  cancelnewBom();
  emits("cancelBomAdd")
}

/**
 * 新增提交
 */
function newBomSubmit(){
  let selectedRows = materialTable.value.getSelectionRows();
  if (selectedRows.length == 0){
    ElMessage({
      type:"warning",
      message:"你没有选中任何数据"
    });
  }else{
    let materialIds = [];
    selectedRows.forEach(row=>{
      materialIds.push(row.materialId);
    })
    console.log(props.materialId)
    console.log(materialIds)
    bomRequest.save(props.materialId,materialIds,res=>{
      if(res.code === 200){
        ElMessage({
          type:"success",
          message:"新增单位成功"
        });
        // 关闭弹窗
        cancelnewBom();
        // 触发编辑完成的事件
        emits('addComplete',res.data);
        // 取消选中
        materialTable.value.clearSelection();
      }
    })
  }
}

/**
 * 侦听器 侦听 props.isShow
 */
watch([() => props.isShow, filterText], ([newIsShow, newFilterText]) => {
  bomAddWinDialogVisible.value = newIsShow;

  if (treeRef.value) {
    treeRef.value.filter(newFilterText);
  }
});


onMounted(() => {
  // 加载物料对象
  loadMaterials();
  // 加载分类对象
  classifyRequest.getTree(0,res=>{
    classifys.value = res.data;
  })
})
</script>
<style scoped>

</style>